package com.qf.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 为了让普通类也可以获取到Spring容器中的实例
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(applicationContext != null){
            SpringUtil.applicationContext = applicationContext;
        }
    }

    // 通过bean的名称获取指定实例
    public static Object getBean(String bean){
        Object obj = applicationContext.getBean(bean);
        return obj;
    }

    // 通过bean的类型，获取指定实例
    public static <T> T getBean(Class<T> clazz){
        T t = applicationContext.getBean(clazz);
        return t;
    }
}
